package com.atguigu.controller;


import com.atguigu.client.CartFeignClient;
import com.atguigu.client.UserFeignClient;
import com.atguigu.entity.CartInfo;
import com.atguigu.entity.OrderDetail;
import com.atguigu.entity.OrderInfo;
import com.atguigu.entity.UserAddress;
import com.atguigu.result.RetVal;
import com.atguigu.service.OrderInfoService;
import com.atguigu.util.AuthContextHolder;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单表 订单表 前端控制器
 * </p>
 *
 * @author zhangqiang
 * @since 2022-01-15
 */
@RestController
@RequestMapping("/order")
public class OrderInfoController {
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private OrderInfoService orderInfoService;
    //1.提供订单确认信息的接口
    @GetMapping("/confirm")
    public RetVal confirm(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //a.地址信息(shop-user)
        List<UserAddress> userAddressList = userFeignClient.getUserAddressByUserId(userId);
        //b.送货清单用户勾选的商品信息(shop-cart)
        List<CartInfo> selectedProductList = cartFeignClient.getSelectedProduct(userId);
        //c.把购物车选中商品进行改造为商品详情

        BigDecimal totalMoney = new BigDecimal(0);
        //商品总共多少件
        int totalNum=0;
        List<OrderDetail> orderDetailArrayList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(selectedProductList)){
            for (CartInfo cartInfo : selectedProductList) {
                OrderDetail orderDetail = new OrderDetail();
                orderDetail.setSkuId(cartInfo.getSkuId());
                orderDetail.setSkuName(cartInfo.getSkuName());
                orderDetail.setImgUrl(cartInfo.getImgUrl());
                orderDetail.setSkuNum(cartInfo.getSkuNum()+"");
                orderDetail.setOrderPrice(cartInfo.getCartPrice());
                //订单总金额
                totalMoney=totalMoney.add(cartInfo.getCartPrice().multiply(new BigDecimal(cartInfo.getSkuNum())));
                totalNum+=cartInfo.getSkuNum();
                orderDetailArrayList.add(orderDetail);
            }
        }

        Map<String, Object> retMap = new HashMap<>();
        //地址信息
        retMap.put("userAddressList",userAddressList);
        //送货清单
        retMap.put("detailArrayList",orderDetailArrayList);
        //订单总金额
        retMap.put("totalMoney",totalMoney);
        //订单总金额
        retMap.put("totalNum",totalNum);
        //b.并且在redis当中也生成一份(为了对比)
        String tradeNo=orderInfoService.generateTradeNo(userId);
        //a.在进入到订单确认页面生成一个流水号
        retMap.put("tradeNo",tradeNo);
        return RetVal.ok(retMap);
    }

    //2.提交订单信息
    @PostMapping("submitOrder")
    public RetVal submitOrder(@RequestBody OrderInfo orderInfo,HttpServletRequest request) {
        //提交以后需要删除redis里面的流水号
        String userId = AuthContextHolder.getUserId(request);
        //从页面当中取出流水号
        String tradeNoUI = request.getParameter("tradeNo");
        //从redis中取出流水号 进行对比
        boolean flag=orderInfoService.checkTradeNo(tradeNoUI,userId);
        if(!flag){
           return RetVal.fail().message("不能无刷新重复提交订单");
        }
        //提交以后需要删除redis里面的流水号
        orderInfoService.deleteTradeNo(userId);
        //验证库存与价格
        List<String> warningInfoList = orderInfoService.checkStockAndPrice(userId, orderInfo);
        if(warningInfoList.size()>0){
            return RetVal.fail().message(StringUtils.join(warningInfoList,","));
        }

        orderInfo.setUserId(Long.parseLong(userId));
        //保存订单信息
        Long orderId = orderInfoService.saveOrderAndDetail(orderInfo);
        return RetVal.ok(orderId);
    }

    //3.根据订单id查询订单信息
    @GetMapping("getOrder/{orderId}")
    public OrderInfo getOrder(@PathVariable Long orderId){
        return orderInfoService.getOrderInfo(orderId);
    }
    //4.拆单接口 http://order.gmall.com/order/splitOrder
    @PostMapping("splitOrder")
    public String splitOrder(@RequestParam Long orderId,@RequestParam String wareHouseIdSkuIdMapJson){
        return orderInfoService.splitOrder(orderId,wareHouseIdSkuIdMapJson);
    }

    //5.封装保存订单信息接口
    @PostMapping("saveOrderAndDetail")
    public Long saveOrderAndDetail(@RequestBody OrderInfo orderInfo){
        return orderInfoService.saveOrderAndDetail(orderInfo);
    }

}

